const express = require('express');

const router = express.Router();

const crypto = require('crypto');

const session = require('express-session');

const multer = require('multer');

const userModel = require('../model/userModel');

// 配置磁盘引擎
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/img'); //    指定文件存放路径
    }, //图片存放地址
    filename: function (req, file, cb) {
        let suffix = file.originalname.split('.'); //取后缀名
        cb(null, Date.now() + '.' + suffix[suffix.length - 1]); // 指定文件名
    } //文件名
});

// 使用磁盘引擎的配置调用方法
const upload = multer({
    storage: storage
});

//渲染注册
router.get('/reg', (req, res) => {
    res.render('reg');
});
router.post('/reg', upload.single('avatar'), (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    let password2 = req.body.password2;
    console.log(req.body, req.file);
    if (username && password) {
        password = crypto.createHmac('sha256', 'vBlog').update(password).digest('hex');
        password2 = crypto.createHmac('sha256', 'vBlog').update(password2).digest('hex');
        if (password !== password2) {
            res.send({
                code: 1,
                msg: '两次输入的密码要相同'
            });
        } else {
            let user = new userModel({
                username,
                password,
                avatar: req.file.filename
            });
            user.save((err, info) => {
                if (err) {
                    console.log(err);                  
                    res.redirect('/user/reg');
                } else {                  
                    res.redirect('/user/login');
                }
            });
        }
    } else {
        return res.send('用户名或密码不能为空~')
    }
    console.log(req.body);
})

//渲染登录
router.get('/login', (req, res, next) => {
    res.render('login');
});
router.post('/login', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    if (username && password) {
        password = crypto.createHmac('sha256', 'vBlog').update(password).digest('hex');
        userModel.find({
            username,
            password
        }, (err, users) => {
            if (err) {
                console.log(err);
                return res.send('登录失败');
            } else {
                if (users.length > 0) {
                    req.session.user = users[0]; //设置session
                    // console.log(users[0]);
                    res.redirect('/article/');
                }
            }
        });
    } else {
        return res.send('用户名或密码错误');
    }
});

//退出登录
router.get('/logout', (req, res) => {
    req.session.destroy(() => {
        res.redirect('/article/');
    });
});


//导出路由器对象
module.exports = router;